package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.NearUserVo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.Near;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLikeApi userLikeApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserService userService;

    /**
     * 接口名称：今日佳人
     * 需求描述：查询缘分值最高的用户。 首页 进入佳人
     */
    public ResponseEntity<Object> queryTodayBest() {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 调用Api服务，根据用户id查询今日佳人
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setRecommendUserId(10L);
            recommendUser.setScore(70D);
        }
        //3. 创建并封装返回的vo对象
        TodayBestVo vo = new TodayBestVo();
        // 调用抽取的方法，实现把recommendUser转换为vo对象
        this.convertRecommendUserToTodayBestVo(recommendUser, vo);
        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：推荐朋友
     * 接口路径：GET/tanhua/recommendation
     * 需求描述：首页 查询推荐用户分页列表
     */
    public ResponseEntity<Object> queryRecommendation(RecommendQueryVo vo) {
        //1. 用户登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 根据登陆用户id，分页查询推荐用户列表
        PageResult pageResult =
                recommendUserApi.queryRecommendation(userId, vo.getPage(), vo.getPagesize());
        //3. 获取分页查询的当前页数据
        List<RecommendUser> list = (List<RecommendUser>) pageResult.getItems();
        if (list == null) {
            // 如果查询为空，推荐用户默认就是id=5-9
            list = new ArrayList<>();
            for (Integer i = 5; i < 10; i++) {
                RecommendUser ru = new RecommendUser();
                ru.setRecommendUserId(i.longValue());
                ru.setScore(70D + i);
                list.add(ru);
            }
        }

        //4. 定义vo集合，封装接口中返回的数据
        List<TodayBestVo> voList = new ArrayList<>();
        //4.1 判断：遍历查询结果
        if (!CollectionUtils.isEmpty(list)) {
            for (RecommendUser recommendUser : list) {
                //4.2 创建vo对象
                TodayBestVo todayBestVo = new TodayBestVo();
                //4.2 封装vo： recommendUser--->todayBestVo
                this.convertRecommendUserToTodayBestVo(recommendUser, todayBestVo);
                //4.3 vo添加到集合
                voList.add(todayBestVo);
            }
        }
        //5. 把封装好的返回的集合数据voList，设置到pageResult中
        pageResult.setItems(voList);
        //6. 返回分页对象
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 抽取方法：实现把RecommendUser推荐用户对象，转换为TodayBestVo对象
     * 使用范围：在首页 推荐今日佳人、推荐用户会调用这个方法
     */
    private void convertRecommendUserToTodayBestVo(
            RecommendUser recommendUser, TodayBestVo vo) {
        //3.1 根据推荐用户id查询用户信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
        //3.2 封装推荐用户信息
        if (userInfo != null) {
            //3.2.1 对象拷贝： userinfo--->vo
            BeanUtils.copyProperties(userInfo, vo);
            //3.2.2 设置tags
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
            //3.2.3 设置缘分值
            vo.setFateValue(recommendUser.getScore().longValue());
        }
    }

    /**
     * 接口名称：佳人信息
     * 接口路径：GET/tanhua/:id/personalInfo
     */
    public ResponseEntity<Object> queryPersonalInfo(Long recommendUserId) {
        // 1. 根据推荐用户id查询
        UserInfo userInfo = userInfoApi.findById(recommendUserId);

        // 2. 根据登陆用户id、推荐用户id查询缘分值
        // db.recommend_user.find({userId:1,recommendUserId:57})
        Long score = recommendUserApi.queryScore(UserHolder.getUserId(), recommendUserId);

        // 3. 封装vo对象
        TodayBestVo vo = new TodayBestVo();
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        vo.setFateValue(score);
        // 4. 返回
        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：查询陌生人问题
     * 接口路径：GET/tanhua/strangerQuestions
     */
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        // 查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        String content = question != null ? question.getTxt() : "你喜欢哪些电影？";
        return ResponseEntity.ok(content);
    }

    /**
     * 接口名称：回复陌生人问题
     * 接口路径：POST/tanhua/strangerQuestions
     * 发送的消息数据格式：
     * {"userId":1,"huanXinId":"1","nickname":"","strangerQuestion":"？","reply":""}
     */
    public ResponseEntity<Object> replyQuestion(Long userId, String reply) {
        //1. 根据登陆用户id查询
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        //2. 查询陌生人问题
        Question question = questionApi.findByUserId(userId);

        //3. 准备消息内容
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userInfo.getId().toString());
        map.put("huanXinId", userInfo.getId());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", question != null ? question.getTxt() : "你喜欢我吗.？");
        map.put("reply", reply);

        //4. map转换为json字符串，并实现发消息
        String result = JSON.toJSONString(map);

        // 调用template工具类，发送消息
        huanXinTemplate.sendMsg(userId.toString(), result);
        return ResponseEntity.ok(null);
    }

    @Reference
    private UserLocationApi userLocationApi;
    /**
     * 接口名称：搜附近
     */
    public ResponseEntity<Object> searchNear(String gender, Long distance) {
        //1. 获取用户id
        Long userId = UserHolder.getUserId();
        //2. 调用Api服务，根据用户id查询附近用户 (RPC 远程调用)
        List<UserLocationVo> list = userLocationApi.searchNear(userId, distance);
        //3. 创建vo集合并返回
        List<NearUserVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (UserLocationVo userLocationVo : list) {
                // 附近的人不能包含自己
                if (userLocationVo.getUserId() == userId) {
                    continue;
                }
                // 根据附近人的用户id查询
                UserInfo userInfo = userInfoApi.findById(userLocationVo.getUserId());
                // 性别筛选
                if (!userInfo.getGender().equals(gender)) {
                    continue;
                }
                // 创建vo对象
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }

    /**
     * 接口名称：探花-喜欢
     */
    public ResponseEntity<Object> likeRecommend(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        /*判断user和likeUser的关系：
        情况1.user和likeUser本来是好友
        情况2: user本来就喜欢likeUser
        情况3.userLike是user的粉丝。
        情况4.user和userLike之间没有关系*/
        Integer relationship = recommendUserApi.getRelationship(userId, likeUserId);
        switch (relationship) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                //调用接口，粉丝 - 喜欢，移除粉丝，到环信注册好友关系
                userService.fanLike(likeUserId);
                break;
            case 4:
                //添加到喜欢列表
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLikeApi.save(userLike);
                break;
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：探花-不喜欢
     */
    public ResponseEntity<Object> unLikeRecommend(Long unLikeUserId) {
        Long userId = UserHolder.getUserId();
        //判断user和likeUser的关系：
        Integer relationship = recommendUserApi.getRelationship(userId, unLikeUserId);
        switch (relationship) {
            case 1://原来是好友关系，删除好友表两条数据，在喜欢表插入一条数据，删除环信好友
                userService.unlike(unLikeUserId);
                break;
            case 2:
                //直接删除喜欢表数据
                userLikeApi.remove(userId, unLikeUserId);
                break;
            case 3:
                break;
            case 4:
                break;
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：左右滑动
     * 返回值为List<UserInfo>
     */
    public ResponseEntity<Object> displayCards() {
        //根据用户id查询推荐用户列表
        Long userId = UserHolder.getUserId();
        List<RecommendUser> list = recommendUserApi.displayCards(userId);

        //封装数据返回
        List<CardVo> CardVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (RecommendUser recommendUser : list) {
                //根据id查用户详情
                Long recommendUserId = recommendUser.getRecommendUserId();
                UserInfo user = userInfoApi.findById(recommendUserId);

                if (user!=null){
                    CardVo cardVo = new CardVo();
                    cardVo.setTags(user.getTags().split(","));
                    BeanUtils.copyProperties(user,cardVo);

                    //添加到CardVos集合中
                    CardVos.add(cardVo);
                }
            }
        }
        return ResponseEntity.ok(CardVos);
    }
}
